import Vue from 'vue'
import Vuex from 'vuex'
import { clearCookie, setCookie, setStore, getStore, clearStore } from '@xingyuelongchen/vue3-storage'
import { logout, login } from '@/api'
import router, { addRouter } from "@/router";
import md5 from 'md5';
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    sideFold: true,
    userinfo: getStore('userinfo') || {},
    menu: []
  },
  mutations: {
    setSideFold(state, bool) {
      state.sideFold = bool
    },
    setUserinfo(state, data) {
      state.userinfo = data;
      setStore('userinfo', data);
    },
    setMenu(state, data) {
      state.menu = data;
    }
  },
  actions: {
    async logout() {
      await logout();
      clearCookie('token');
      clearStore();
      window.location.href = '/'
    },
    async login({ commit }, data) {
      let { username, password } = data;
      let res = await login({ username, password: md5(password) });
      if (res.data.code === 200) {
        setCookie('token', res.data.data.token);
        setStore('menuTree', res.data.data.menu);
        commit('setUserinfo', res.data.data.userinfo);
        await addRouter(res.data.data.menu);
        router.replace("/");
      }
    }
  },
  modules: {
  }
})
